<?php

/*
 * Author: Quan Van Sinh
 * Email : qvsinh@gmail.com
 * Mobile: 0972405165
 */

class money {

    function money() {
        
    }

    function add_expense() {
        global $db, $common;
        if (isset($_POST['money_date'])) {
            $mid = $_SESSION['client']['id'];
            $can_insert = TRUE;
            $money_date = trim($_POST['money_date']);
            $money = intval(str_replace('.', '', trim($_POST['money'])));
            $note = trim($_POST['note']);
            $created = date("Y-m-d H:i:s");
            if (trim($_GET['action']) == 'ke-hoach-chi-tieu') {
                $type = 1;
            } elseif (trim($_GET['action']) == 'theo-doi-thu-nhap') {
                $type = 3;
            } else {
                $type = 2;
            }
            if (empty($money_date) || $money_date == '') {
                $can_insert = FALSE;
                $common->set_notify('error', 'Bạn chưa chọn ngày tiêu tiền!');
            }
            if ($money == 0) {
                $can_insert = FALSE;
                $common->set_notify('error', 'Bạn chưa nhập số tiền đã tiêu!');
            }
            if ($can_insert) {
                $data = array();
                $data['mid'] = $mid;
                $data['money_date'] = $money_date;
                $data['money'] = $money;
                $data['note'] = $note;
                $data['type'] = $type;
                $data['created'] = $created;
                $db->exec_insert('money', $data);
                $id = $db->mysql_insert_id();
                if (trim($_GET['action']) == 'ke-hoach-chi-tieu') {
                    $common->set_notify('success', 'Bạn đã thêm vào mục kế hoạch chi tiêu thành công!');
                } elseif (trim($_GET['action']) == 'theo-doi-thu-nhap') {
                    $common->set_notify('success', 'Bạn đã thêm vào mục theo dõi thu nhập thành công!');
                } else {
                    $common->set_notify('success', 'Bạn đã thêm vào mục theo dõi chi tiêu thành công!');
                }
                
                return $id;
            } else {
                return FALSE;
            }
        }
    }

    function list_expense_by_month() {
        global $db;
        $month = 0;
        $year = 0;
        if (isset($_GET['date'])) {
            $arr_year_month = explode('-', $_GET['date']);
            if (intval($arr_year_month[0]) && strlen(intval($arr_year_month[0])) == 4 && intval($arr_year_month[1]) && (intval($arr_year_month[1]) >= 1 && intval($arr_year_month[1]) <= 12)) {
                $month = intval($arr_year_month[1]);
                $year = intval($arr_year_month[0]);
            }
        }
        if ($month == 0) {
            $month = date('m');
        }
        if ($year == 0) {
            $year = date('Y');
        }
        $mid = $_SESSION['client']['id'];

        if ($month == 12) {
            $nextMonth = 1;
            $nextYear = $year + 1;
        } else {
            $nextMonth = $month + 1;
            $nextYear = $year;
        }
        $currentDate = $year . '-' . $month;
        $nextDate = $nextYear . '-' . $nextMonth;
        if (trim($_GET['action']) == 'ke-hoach-chi-tieu') {
            $type = 1;
        } elseif (trim($_GET['action']) == 'theo-doi-thu-nhap') {
            $type = 3;
        } else {
            $type = 2;
        }
        $sql = "SELECT * FROM money WHERE mid=$mid AND type=$type AND money_date >= '$currentDate' AND money_date < '$nextDate' ORDER BY money_date";
        $rs = $db->query($sql);
        $result = array();
        $totalMoney = 0;
        while ($row = $db->fetch_array($rs)) {
            $result[$row['id']] = $row;
            $totalMoney = $totalMoney + $row['money'];
        }
        return array('arrRs' => $result, 'totalMoney'=>$totalMoney);
    }

    function delete_money($id) {
        global $db;
        $mid = $_SESSION['client']['id'];
        $sql = "DELETE FROM money where id=$id AND mid=$mid";
        $rsCheck = $db->query($sql);
        return $db->affected_rows();
    }

    function listMyImage($limit=50) {
        global $db;
        $mid = intval($_GET['mid']);
        $aid = intval($_GET['aid']);
        if ($mid && $aid) {
            $page = intval($_GET['page']);
            if ($page < 1) {
                $page = 1;
            }

            $sql = "SELECT count(*) as numrows FROM images WHERE mid=$mid AND aid=$aid and active=1";
            $arrTotalRows = $db->query_first($sql);
            $totalPages = ceil($arrTotalRows['numrows'] / $limit);
            $start = (($page * $limit) - $limit);

            $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$aid and active=1 LIMIT $start,$limit";
            $rs = $db->query($sql);

            $sql = "SELECT * FROM album WHERE id=$aid";
            $arrAlbum = $db->query_first($sql);
            return array('rs' => $rs, 'arrAlbum' => $arrAlbum, 'page' => $page, 'totalPage' => $totalPages);
        } else {
            return false;
        }
    }

    function getMyImageExcept($mid, $album_id, $except_id, $limit=9) {
        global $db;
        if ($mid && $album_id) {
            $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$album_id AND id!=$except_id and active=1 LIMIT 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return false;
        }
    }

    function viewImage() {
        global $db;
        $mid = intval($_GET['mid']);
        $aid = intval($_GET['aid']);
        $image_id = intval($_GET['image_id']);

        $sql = "SELECT * FROM images WHERE mid=$mid AND aid=$aid AND id=$image_id LIMIT 1";
        $arrRs = $db->query_first($sql);

        if ($arrRs['id']) {
            $db->query("UPDATE images SET num_views=num_views+1 WHERE id = $image_id");
        }

        $sqlComment = "SELECT * FROM image_comment WHERE 1 AND image_id=$image_id";
        $rsComment = $db->query($sqlComment);

        $sql = "SELECT * FROM images WHERE mid=$mid  AND aid=$aid AND id<$image_id ORDER BY id DESC LIMIT 1";
        $arrPre = $db->query_first($sql);

        $sql = "SELECT * FROM images WHERE mid=$mid  AND aid=$aid AND id>$image_id ORDER BY id LIMIT 1";
        $arrNext = $db->query_first($sql);

        return array('arrRs' => $arrRs, 'rsComment' => $rsComment, 'arrPre' => $arrPre, 'arrNext' => $arrNext);
    }

    function profile() {
        global $db;

        $mid = intval($_GET['mid']);
        $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$mid";
        if ($mid) {
            $profile = $db->query_first($sql);
            if ($profile['geo_id']) {
                $sqlGeo = "SELECT * FROM geographic WHERE id=" . $profile['geo_id'];
                $arrGeo = $db->query_first($sqlGeo);
                $profile['city_id'] = intval($arrGeo['parent_id']);
                $sqlDistricts = "SELECT * FROM geographic WHERE parent_id=" . $profile['city_id'];
                $rsDistricts = $db->query($sqlDistricts);
            }
            return array('profile' => $profile, 'rsDistricts' => $rsDistricts);
        }
    }

    function getAvatar() {
        global $db;
        $mid = $_SESSION['client']['id'];
        $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$mid";
        $rs = $db->query_first($sql);
        return $rs['avatar'];
    }

    function getById($id) {
        global $db;
        if ($id > 0) {
            $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member where id=$id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getByName($name) {
        global $db;
        if (strlen(trim($name)) > 0) {
            $sql = "SELECT id,CONCAT(first_name,' ',last_name) as name,email,avatar FROM member where CONCAT(first_name,' ',last_name) like '%$name%' and  LIMIT 10";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getFriendByName($name) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (strlen(trim($name)) > 0) {
            $sql = "SELECT m.id,CONCAT(first_name,' ',last_name) as name,email,avatar FROM member as m inner join friend as f on m.id=f.friend_id where f.mid=$mid AND CONCAT(first_name,' ',last_name) like '%$name%'";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getGeoById($geo_id) {
        global $db;
        if (intval($geo_id)) {
            $sql = "SELECT * FROM geographic WHERE id=$geo_id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAlbumById() {
        global $db;
        $albumId = intval($_GET['id']);
        $mid = $_SESSION['client']['id'];
        if (intval($albumId)) {
            $sql = "SELECT * FROM album WHERE id=$albumId AND mid=$mid";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function updateImageView($image_id) {
        global $db;
        if (intval($image_id)) {
            $sql = "UPDATE image SET num_views=num_views+1 WHERE id=$image_id";
            $rs = $db->query($sql);
            return TRue;
        } else {
            return FALSE;
        }
    }

    function getAllAlbum() {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT * FROM album WHERE mid=$mid";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAllGroup() {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT * FROM groups WHERE mid=$mid";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getAllFriend($limit=30) {
        global $db;
        $mid = $_GET["mid"];
        $geo_id = $_SESSION['client']['geo_id'];
        if (intval($mid)) {
            $sql = "SELECT m.*,CONCAT(first_name,' ', last_name) as fullname,groups from member m inner join friend f on m.id=f.friend_id where f.mid=$mid order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getNotFriend($limit) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname from member where id NOT in (select friend_id FROM friend WHERE mid=$mid) and id!=$mid order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getFriendInGroup($gid, $limit) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $sql = "SELECT m.id as mid,m.avatar,CONCAT(first_name,' ', last_name) as fullname from member as m inner join friend as f on m.id=f.friend_id where groups like '%|$gid|%' order by fullname limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function addGroup($groupName, $groupDesc='') {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {

            $data = array();
            $data['group_name'] = $groupName;
            $data['length'] = 0;
            $data['mid'] = $mid;
            $data['description'] = $groupDesc;

            $db->exec_insert('groups', $data);
            $group_id = $db->mysql_insert_id();
            return $group_id;
        } else {
            return FALSE;
        }
    }

    function deleteGroup($group_id) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid) && $group_id) {
            $sql = "SELECT * FROM groups where id=$group_id";
            $rsCheck = $db->query_first($sql);
            if ($rsCheck['length'] > 0) {
                return 'not_empty';
            } else {
                $sql = "DELETE FROM groups where id=$group_id";
                $rsCheck = $db->query($sql);
                return 'ok';
            }
        } else {
            return FALSE;
        }
    }

    function addFriend($friendID, $group_id="") {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $data = array();
            $data['friend_id'] = $friendID;
            $data['groups'] = "|" . $group_id . "|";
            $data['mid'] = $mid;


            $sql = "SELECT * from friend where mid=$mid and friend_id=$friendID";
            $rs = $db->query($sql);

            if ($db->num_rows($rs) <= 0) {
                $db->exec_insert('friend', $data);
                if ($group_id > 0)
                    $db->query("UPDATE groups SET length=length+1 WHERE id=$group_id");
            } else {
                $rsCheck = $db->query("SELECT * from friend where mid=$mid and friend_id=$friendID and groups like '%|" . $group_id . "|%'");
                if ($db->num_rows($rsCheck) <= 0) {
                    $db->query("UPDATE friend SET groups=concat(groups,'" . $group_id . "|') WHERE mid=$mid and friend_id=$friendID");
                    if ($group_id > 0)
                        $db->query("UPDATE groups SET length=length+1 WHERE id=$group_id");
                } else {
                    return '0';
                }
            }
            return '1';
        } else {
            return '-1';
        }
    }

    function removeFriendFromGroup($friendID, $group_id) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if (intval($mid)) {
            $updatesql = "UPDATE friend SET groups=replace(groups,'" . $group_id . "|','') WHERE mid=$mid and friend_id=$friendID and groups like '%|" . $group_id . "|%'";
            $db->query($updatesql);
            if ($group_id > 0)
                $db->query("UPDATE groups SET length=length-1 WHERE id=$group_id");
            return '1';
        } else {
            return '-1';
        }
    }

    function searchFriend($keyword, $group_id="", $limit=50) {
        global $db;
        $mid = $_SESSION['client']['id'];
        if ($group_id != "")
            $group_id = "|" . $group_id . "|";
        if (intval($mid)) {
            $sql = "SELECT m.*,CONCAT(first_name,' ', last_name) as fullname FROM member as m inner join friend as f on m.id=f.friend_id WHERE f.mid=$mid and CONCAT(first_name,' ', last_name) LIKE '%$keyword%' and groups like '%$group_id%' order by CONCAT(first_name,' ', last_name) limit 0,$limit";
            $rs = $db->query($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function searchMember($limit=NUM_ROW_PER_PAGE) {
        global $db;
        include_once MODEL_DIR . 'validate.class.php';
        $validate = new validate();
        $mid = $_SESSION['client']['id'];
        $geo_id = intval($_SESSION['client']['geo_id']);
        $keyword = trim(mysql_real_escape_string($_GET['keyword']));
        if ($keyword) {
            if ($validate->email($keyword)) {
                $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND email='$keyword'";
                $rs = $db->query($sql);
                return array(
                    'rs' => $rs,
                    'totalPage' => 1,
                    'page' => 1
                );
            } else if (intval($mid)) {

                $page = intval($_GET['page']);
                if ($page <= 0) {
                    $page = 1;
                }

                $sqlTotal = "SELECT count(id) as total FROM member WHERE 1 AND id!=$mid AND CONCAT(first_name,' ', last_name) LIKE '%$keyword%'";
                $totalRow = $db->query_first($sqlTotal);
                $totalPage = ceil($totalRow['total'] / NUM_ROW_PER_PAGE);
                $start = (($page * NUM_ROW_PER_PAGE) - NUM_ROW_PER_PAGE);

                $sql = "SELECT *,CONCAT(first_name,' ', last_name) as fullname FROM member WHERE 1 AND id!=$mid AND  CONCAT(first_name,' ', last_name) LIKE '%$keyword%' limit $start,$limit";
                $rs = $db->query($sql);

                return array(
                    'rs' => $rs,
                    'totalPage' => $totalPage,
                    'page' => $page
                );
            } else {
                return FALSE;
            }
        }
    }

    function getNotifyImage($mid, $imgIds, $limit=3) {
        global $db;
        $rs = FALSE;
        if ($imgIds) {
            $sql = "SELECT * FROM images WHERE 1 AND mid=$mid AND id IN ($imgIds) AND active=1 ORDER BY id DESC LIMIT $limit";
            $rs = $db->query($sql);
        }
        return $rs;
    }

    function getMemberByGroupId($group_id) {
        global $db;
        $rs = FALSE;
        if ($group_id) {
            $sql = "SELECT * FROM friend WHERE 1 AND groups LIKE '%|$group_id|%'";
            $rs = $db->query($sql);
        }
        return $rs;
    }

    function getByImageId($id) {
        global $db;
        if ($id > 0) {
            $sql = "SELECT * FROM images where id=$id";
            $rs = $db->query_first($sql);
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getImageCommentByImageId($image_id) {
        global $db;
        if ($image_id > 0) {
            $sqlComment = "SELECT * FROM image_comment WHERE 1 AND image_id=$image_id";
            $rsComment = $db->query($sqlComment);
            while ($row = $db->fetch_array($rsComment)) {
                $rs[$row['mid']] = $row;
            }
            return $rs;
        } else {
            return FALSE;
        }
    }

    function addActivities($mid, $content) {
        global $db;
        if ($mid && !empty($content)) {
            $data = array();
            $data['mid'] = $mid;
            $data['content'] = $content;
            $data['create_date'] = date('Y-m-d h:i:s');
            $db->exec_insert("activities", $data);
        }
    }

    function getActivities($limit=10) {
        global $db;

        $mid = $_SESSION['client']['id'];
        $rs = array();
        if ($mid) {
            $sql = "SELECT * FROM activities WHERE 1 AND mid!=$mid ORDER BY id DESC LIMIT $limit";
            $rsA = $db->query($sql);
            while ($row = $db->fetch_array($rsA)) {
                $memberInfo = $this->getById($row['mid']);
                $row['memInfo'] = $memberInfo;
                $rs[] = $row;
            }
            return $rs;
        } else {
            return FALSE;
        }
    }

    function getActivitiesByLastId($last_id, $limit=10) {
        global $db;

        $mid = $_SESSION['client']['id'];
        $rs = array();
        if ($mid) {
            $sql = "SELECT * FROM activities WHERE 1 AND id<$last_id AND mid!=$mid ORDER BY id DESC LIMIT $limit";
            $rsA = $db->query($sql);
            while ($row = $db->fetch_array($rsA)) {
                $memberInfo = $this->getById($row['mid']);
                $row['memInfo'] = $memberInfo;
                $rs[] = $row;
            }
            return $rs;
        } else {
            return FALSE;
        }
    }
    
    function format_money($money){
        $rsMoney = '';
        $arrChar = str_split(strrev($money));
        $i=0;
        foreach($arrChar as $value){
            $i++;
            if($i==3){
                $i=0;
                $rsMoney .= $value.'.';
            }else{
                $rsMoney .= $value;
            }
        }
        return trim(strrev($rsMoney),'.');
    }

}

?>
